import React, { Component } from "react"
import ReactDOM from 'react-dom';
import { ListView, Toast, List, Modal, Button } from "antd-mobile";
import { animateScroll as scroll } from "react-scroll";
import PubSub from "pubsub-js";
import {
    addAudio,
    getAudiosByAlbum,
    addAlbum,
    removeAlbum,
    getDeviceId,
    getAlbumInfo,
    getDeviceSn,
    getTrackList,
    getUuid,
    convetAudiosByAlbum
} from "../utils";
import AudioItem from "../components/AudioItem";
import "../css/nas.css";
import { COMMON_CATEGORY_ID, BAIDU_CATEGORY_ID } from '../config';

// 主界面音频列表展示,不进行删除操作
class SingleAlbum extends Component {

    constructor(props, context) {
        super(props, context);
        const ds = new ListView.DataSource({
            rowHasChanged: (row1, row2) => row1 !== row2,
        })

        this.handleRemotePlay = this.handleRemotePlay.bind(this);
        this.checkStoreState = this.checkStoreState.bind(this);
        this.handleAdd = this.handleAdd.bind(this);
        this.scroll = this.scroll.bind(this);
        this.handleScrollTo = this.handleScrollTo.bind(this);

        this.handleAdd = this.handleAdd.bind(this);
        // 数据
        this.device_id = getDeviceId();
        let album = this.props.location.album;
        let fromBaidu = this.props.location.fromBaidu || false;
        this.left = document.documentElement.clientWidth - 55;

        // 获取收藏的类别
        const categoryList = JSON.parse(localStorage.getItem('category_list')) || [];
        this.state = {
            album: album,
            audios: [],
            count: 0,
            dataSource: ds.cloneWithRows([]),
            height: document.documentElement.clientHeight * 3,
            fromBaidu: fromBaidu,  // 是否为百度搜索资源
            hasCheck: true,
            hiddenBackTop: true,
            hasMore: true,
            isLoading: true,
            upid: 0,  // 百度数据分页
            showSheet: false,
            audio: null,
            index: null,
            categoryList: categoryList
        }
        this.startTime = 0;
    }

    componentDidMount() {
        this._mounted = true;
        if (this.lv) {
            let hei = document.documentElement.clientHeight - ReactDOM.findDOMNode(this.lv).parentNode.offsetTop;
            this.setState({
                height: hei,
            });
        }
        if (this.state.album.name) {
            this.getAudioList();
        } else {
            getAlbumInfo(this.state.album.album_id, (data) => {
                if (data.errcode === 0 && data.data.length > 0) {
                    this.setState({
                        album: data.data[0]
                    });
                    this.getAudioList();
                }
            })
        }
        window.addEventListener("scroll", this.scroll);
    }

    // 滑动事件监听
    scroll(event) {
        let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
        if (scrollTop >= 180) {
            if (this.state.hiddenBackTop) {
                this.setState({ hiddenBackTop: false });
            }
        } else if (scrollTop <= 180 && !this.state.hiddenBackTop) {
            this.setState({ hiddenBackTop: true });
        }
    }

    scrollToTop() {
        scroll.scrollToTop({ duration: 200 });
    }

    componentWillUnmount() {
        this._mounted = false;
        window.removeEventListener("scroll", this.scroll);
    }

    eventDispatch() {
        const end = new Date().getTime();
        if (end - this.startTime <= 200) {
            this.startTime = end;
            return true;
        }
        this.startTime = end;
        return false;
    }

    onEndReached = (event) => {
        if (this.state.isLoading && !this.state.hasMore) {
            return;
        }
        if (this.eventDispatch()) {
            return;
        }
        this.getAudioList();
    }

    getAudioList() {
        this.setState({ isLoading: true });
        if (this.state.fromBaidu) {
            getTrackList(getUuid(), this.state.album.album_id, 21, this.state.upid, (result) => {
                if (!this._mounted) {
                    return;
                }
                if (result.errcode === 0 && result.data) {
                    let audios = convetAudiosByAlbum(result.data)
                    if (audios.length > 0) {
                        const newAudios = this.state.audios.concat(audios)
                        const upid = audios[audios.length - 1].episode
                        this.setState({
                            audios: newAudios,
                            dataSource: this.state.dataSource.cloneWithRows(newAudios),
                            isLoading: false,
                            hasMore: audios.length >= 20,
                            upid: upid
                        });
                    } else {
                        this.setState({ isLoading: false, hasMore: false });
                    }
                } else {
                    this.setState({ isLoading: false, });
                }
            })
        } else {
            getAudiosByAlbum(this.state.album.album_id, this.state.upid, this.state.count, (data) => {
                if (!this._mounted) {
                    return;
                }
                console.log(JSON.stringify(data.data));
                if (data.errcode === 0) {
                    const len = data.data.length;
                    if (len > 0) {
                        const newAudios = this.state.audios.concat(data.data);
                        const audio = data.data[len - 1];
                        this.category_id = audio.category_id;
                        let albumCount = this.state.count;
                        if (albumCount === 0) {
                            albumCount = audio.count;
                        }
                        this.setState({
                            audios: newAudios,
                            dataSource: this.state.dataSource.cloneWithRows(newAudios),
                            isLoading: false,
                            hasMore: len >= 20,
                            upid: audio.id,
                            count: albumCount
                        });
                        this.checkStoreState(newAudios);
                    } else {
                        this.setState({ isLoading: false, hasMore: false });
                    }
                } else {
                    this.setState({ isLoading: false, });
                }
            });
        }
    }

    // 远程播放
    handleRemotePlay(audio) {
        if (this.notBind()) {
            return;
        }
        const img_url = this.state.album.img_url;
        const albumName = this.state.album.name;
        const audioListCount = this.state.album.count ? this.state.album.count : this.state.count;
        const audioList = this.state.audios.map((audio) => {
            return Object.assign(audio, {
                img_url: img_url,
                album_name: albumName,
                album_count:audioListCount
            })
        })
        PubSub.publish("remotePlay", { category_id: this.state.fromBaidu ? BAIDU_CATEGORY_ID : COMMON_CATEGORY_ID, audio: audio, audioList: audioList });
    }

    // 第一次加载数据,如果全都为添加的话,那么现实移除
    // 先获取第一个数据的状态
    checkStoreState(audioList = this.state.audios) {
        if (getUuid() === '') {
            this.setState({ hasCheck: true });
            return;
        }
        const index = audioList.findIndex((audio) => {
            return audio.uuid !== getUuid();
        });
        this.setState({ hasCheck: index !== -1 });
    }


    notBind() {
        if (getDeviceSn()) {
            return false;
        }
        Toast.show("未绑定设备", 1, false);
        return true;
    }

    updateAllAudio(hasCheck,category_id) {
        const newAudioList = this.state.audios.map((audio) => {
            return Object.assign(audio, { uuid: hasCheck ? getUuid() : null,store_category_id:category_id});
        })
        const ds = new ListView.DataSource({
            rowHasChanged: (row1, row2) => row1 !== row2,
        })
        this.setState({
            audioList: newAudioList,
            dataSource: ds.cloneWithRows(newAudioList),
            hasCheck: !hasCheck
        });
    }

    handleScrollTo() {
        this.scrollToTop();
    }

    onClose = key => () => {
        this.setState({
            showSheet: false,
            audio: null,
            index: null
        });
    }

    // 点击事件处理
    handleAddAudio = (category_id) => {
        if (this.state.index === -1) {
            addAlbum(this.state.album.album_id,category_id, (data) => {
                if (data.errcode === 0) {
                    Toast.show("添加成功", 1)
                    this.updateAllAudio(this.state.hasCheck,category_id);
                } else {
                    Toast.show("添加失败", 1);
                }
                this.setState({
                    showSheet: false,
                    audio: null,
                    index: null
                });
            })
        } else {
            const audio_id = this.state.audio.audio_id;
            addAudio(audio_id, category_id, (data) => {
                if (data.errcode === 0) {
                    const newAudio = Object.assign(this.state.audio, { uuid: getUuid(),store_category_id: category_id});
                    const ds = new ListView.DataSource({
                        rowHasChanged: (row1, row2) => row1 !== row2,
                    })
                    let newAudioList = this.state.audios;
                    newAudioList[this.state.index] = newAudio;
                    this.setState({
                        audioList: newAudioList,
                        dataSource: ds.cloneWithRows(newAudioList),
                    });
                    this.checkStoreState(newAudioList);
                }
                this.setState({
                    showSheet: false,
                    audio: null,
                    index: null
                });
            });
        }
    }

    handleAdd(item) {
        if (this.notBind()) {
            Toast.show('还未绑定设备',1,false);
            return;
        }
        let index = -1;
        let audio = null;
        if (item.audio) {
            index = item.index;
            audio = item.audio;
        }else {
            if (!this.state.hasCheck) {
                const store_category_id = this.state.audios[0].store_category_id;
                removeAlbum(this.state.album.album_id,store_category_id, (data) => {
                    if (data.errcode === 0) {
                        Toast.show("移除成功", 1);
                        this.updateAllAudio(this.state.hasCheck,store_category_id);
                    } else {
                        Toast.show("移除失败", 1);
                    }
                })
                return;  
            }
        }
        this.setState({
            showSheet: true,
            audio: audio,
            index: index
        });
    }



    render() {
        let row = (rowData, sectionID, rowID) => {
            return (
                <AudioItem
                    key={"" + rowID}
                    audio={rowData}
                    index={parseInt(rowID, 10)}
                    device_id={this.device_id}
                    hiddenRight={this.state.fromBaidu}
                    categoryId={this.category_id}
                    handleRemotePlay={this.handleRemotePlay}
                    checkStoreState={this.checkStoreState}
                    handleAdd={this.handleAdd} />
            );
        };

        return (
            <div>
                <div style={{
                    position: "fixed",
                    display: "flex",
                    textAlign: "center",
                    justifyContent: "center",
                    top: "20px",
                    width: "25px",
                    height: "25px",
                    marginLeft: this.left,
                    backgroundColor: "#424242",
                    opacity: 0.7,
                    borderRadius: "5px",
                    color: "#ffffff",
                    fontSize: "11px",
                    padding: "7px",
                    visibility: this.state.hiddenBackTop ? "hidden" : "visible",
                    lineHeight: 1.2,
                    zIndex: 10,
                }} onClick={this.handleScrollTo.bind(this)}>
                    <span>返回顶部</span>
                </div>

                <div style={{ background: "#FAFAFA", width: "100%", height: "100%" }}>

                    <div style={{ height: "180px", width: "100%" }}>
                        <div style={{ width: "100%", height: "180px", position: "absolute" }}>
                            <div className="container-album-bg" style={{ backgroundImage: `url(${this.state.album.img_url})` }} />
                            <div className="album_img">
                                <div style={{ height: "180px", width: "100%", display: "flex", justifyContent: "center", alignItems: "center" }}>
                                    <div style={{ height: "130px", width: "100px", textAlign: "center" }}>
                                        <img src={this.state.album.img_url} style={{ height: "100px", width: "100px", borderRadius: "6px" }} alt="" />
                                        <span>{this.state.album.name}</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div style={{ height: "46px", width: "100%", background: "#ffffff", position: "absolute", zIndex: 4 }}>
                        <div style={{ height: "46px", width: "100%", display: "flex" }}>
                            <div style={{ width: "100%", height: "46px" }}>
                                <p style={{ marginTop: "13px", marginLeft: "10px", color: "#616161" }}>专辑曲目({this.state.album.count ? this.state.album.count : this.state.count})</p>
                            </div>
                            <div style={{ display: "flex", justifyContent: "center", alignItems: "center", height: "46px", position: "none" }}>
                                {
                                    !this.state.fromBaidu && <Button
                                        inline
                                        size="small"
                                        style={{ marginRight: "6px", marginBottom: "2px", fontSize: "12px", color: "#9E9E9E" }}
                                        onClick={this.handleAdd}>{this.state.hasCheck ? "添加全部" : "移除全部"}</Button>
                                }
                            </div>
                        </div>
                    </div>
                    <div style={{ paddingBottom: "0px", marginTop: "46px", background: "#f5f5f9" }}>
                        <ListView
                            ref={el => this.lv = el}
                            dataSource={this.state.dataSource}
                            renderFooter={() => (
                                <div style={{
                                    padding: "16px",
                                    textAlign: 'center',
                                    fontSize: '13px',
                                }}>
                                    {this.state.hasMore ? "正在加载内容..." : '没有更多内容了~'}
                                </div>)}
                            renderRow={row}
                            initialListSize={2000}
                            useBodyScroll={true}
                            className="am-list"
                            scrollEventThrottle={100}
                            scrollRenderAheadDistance={300}
                            onEndReached={this.onEndReached}
                            onEndReachedThreshold={20}
                        />

                    </div>
                </div>
                <Modal
                    popup
                    visible={this.state.showSheet}
                    maskClosable
                    onClose={this.onClose()}
                    animationType="slide-up"
                >
                    <div style={{ display: "flex", height: "42px", width: "100%", background: '#eeeeee' }}>
                        <div style={{ width: "15%" }} />
                        <div style={{ width: "70%", display: "flex", alignItems: "center", justifyContent: 'center' }} >
                            <span>请选择播放列表</span>
                        </div>
                        <div style={{ width: "15%", color: "#15a67c", display: "flex", alignItems: "center", justifyContent: 'center' }} onClick={this.onClose()} >
                            <span>取消</span>
                        </div>
                    </div>
                    <List>
                        {this.state.categoryList.map((item, index) => (
                            <List.Item key={index} onClick={this.handleAddAudio.bind(this, item.category_id)}>{item.title}</List.Item>
                        ))}
                    </List>
                </Modal>
            </div>

        );
    }
}

export default SingleAlbum;
